package com.sb.controller;

import com.sb.async.AsyncTaskService;
import com.sb.crawler.ActionTriggerServiceFactory;
import com.sb.crawler.BaseCrawler;
import com.sb.entity.ActionContext;
import com.sb.entity.Result;
import com.sb.entity.SBPageInfo;
import com.sb.entity.User;
import com.sb.enums.StateCodeEnum;
import com.sb.manage.SBPageInfoManage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by wujunzhou on 2017/10/18.
 */
@Controller
@RequestMapping("/sb")
@Configuration
public class SBController extends WebMvcConfigurerAdapter {
    private  final Logger logger= LoggerFactory.getLogger(SBController.class);

    ThreadLocal<BaseCrawler> authContext = new ThreadLocal<>();
    ThreadLocal<User> userContext = new ThreadLocal<>();
    @Autowired
    private ActionTriggerServiceFactory actionTriggerServiceFactory;
    @Autowired
    private SBPageInfoManage sbPageInfoManage;

    /**
     * 社保列表
     *
     * @param map
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpSession httpSession,ModelMap map,User user) {
        httpSession.setAttribute("user", user);
        return "sb/list";
    }
    @RequestMapping(value = "/getSBPageInfoList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    Result getSBPageInfoList(){
        Result result = new Result();
        try {
            result.setSuccess(Result.SUCCESS);
            result.setErrorCode(StateCodeEnum.STATE_CODE_200.getCode());
            result.setErrorMsg("ok");
            List<SBPageInfo> sbPageInfoList = sbPageInfoManage.getSBPageInfoList();
            result.setData(sbPageInfoList);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(StateCodeEnum.STATE_CODE_403.getCode());
            result.setErrorMsg("获取列表失败");
            logger.info("获取列表失败，msg:"+e.getMessage(),e);
        }
        return result;
    }
    /**
     * 返回表单信息
     * @param key
     * @return
     */
    @RequestMapping(value = "/getSBPageInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    Result getSBPageInfo(HttpSession httpSession, String key){
        Result result = new Result();
        try {
            BaseCrawler baseCrawler = actionTriggerServiceFactory.getTriggerService(key);
            httpSession.setAttribute("baseCrawler", baseCrawler);
            result.setSuccess(Result.SUCCESS);
            result.setErrorCode(StateCodeEnum.STATE_CODE_200.getCode());
            result.setErrorMsg("ok");
            SBPageInfo sbPageInfo = sbPageInfoManage.getSBPageInfoByKey(key);
            result.setData(sbPageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(StateCodeEnum.STATE_CODE_403.getCode());
            result.setErrorMsg("获取表单信息失败");
            logger.info("获取表单信息失败，msg:"+e.getMessage(),e);
        }
        return result;
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET, produces = MediaType.ALL_VALUE)
    public String index(ActionContext actionContext, ModelMap map) {
        map.put("user",userContext.get());
        return "sb/index";
    }
    @RequestMapping(value = "/crawler", method = {RequestMethod.GET,RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    Result crawler(ActionContext actionContext){
        Result result = new Result();
        try {
            actionContext.setUser(userContext.get());
            result =  authContext.get().crawler(actionContext);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(StateCodeEnum.STATE_CODE_403.getCode());
            result.setErrorMsg("网络错误");
            logger.info("网络错误，msg:"+e.getMessage(),e);
        }
        return result;
    }

    @RequestMapping(value = "/success")
    public String success(String msg, ModelMap map) {
        map.put("msg1",msg);
        return "sb/success";
    }


    /**
     * 验证码图片
     *
     * @param actionContext
     * @param map
     * @return
     */
    @RequestMapping("/getCaptcha")
    public
    @ResponseBody
    byte[] getCaptcha(ActionContext actionContext, ModelMap map) {
        return authContext.get().getCaptcha();
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/sb/list");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }

    //      此方法会在每次请求前调用（这个类的处理方法）
    @ModelAttribute
    public void initBaseCrawler(HttpSession session) {
        Object obj = session.getAttribute("baseCrawler");
        if (obj instanceof BaseCrawler) {
            BaseCrawler user = (BaseCrawler) obj;
            authContext.set(user);
        }
        Object obj1 = session.getAttribute("user");
        if (obj1 instanceof User) {
            User user = (User) obj1;
            userContext.set(user);
        }
    }
}

